﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Markup;
using MvvmEx.Helpers;

namespace MvvmEx.MarkupExtension
{
    /// <summary>
    /// 根据枚举值转换成字典使用
    /// </summary>
    [MarkupExtensionReturnType(typeof(object[]))]
    public class EnumToDicMarkupExtension : System.Windows.Markup.MarkupExtension
    {
        public EnumToDicMarkupExtension()
        {

        }

        public EnumToDicMarkupExtension(Type enumType)
        {
            this.EnumType = enumType;
        }

        [ConstructorArgument("enumType")]
        public Type EnumType { get; set; }

        /// <summary>
        /// 排除的枚举值，用,间隔
        /// </summary>
        public bool ExcludeFirst { get; set; }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            try
            {
                var dic = new Dictionary<string, Enum>();

                var enumObjs = Enum.GetValues(EnumType);

                var i = 0;

                foreach (Enum enumObj in enumObjs)
                {
                    if (ExcludeFirst && i == 0)
                    {
                        i++;
                        continue;
                    }

                    var des = EnumHelper.GetEnumDescription(enumObj);

                    if (!dic.ContainsKey(des))
                    {
                        dic.Add(des, enumObj);
                    }

                    i++;
                }

                return dic;
            }
            catch (Exception ex)
            {
                return new Dictionary<string, Enum>();
            }
        }
    }
}